﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using JHSoft.IDAL;
using System.Text.RegularExpressions;
using Microhard.Workflow.Interfaces;

namespace Microhard.JHWorkflow
{
    public class JHWorkflowTool
    {
        /// <summary>
        /// 暂存
        /// </summary>
        /// <param name="strAppTID">审批类型</param>
        /// <param name="intAppID">appID</param>
        /// <param name="intIdeaFlag">意见标志</param>
        /// <param name="strAppIdea">审批意见</param>
        /// <param name="strDisCode">审批人ID</param>
        /// <param name="strUserCode">用户CODE</param>
        /// <param name="strAppDSIDs">拟办同步</param>
        /// <param name="strAppDSIDMs">拟办出口</param>
        /// <param name="strObject">被审批的更新参数</param>
        /// <param name="strAppOTitle">业务标题</param>
        /// <param name="InstanceID">流程实例ID</param>
        /// <returns>返回1成功0失败</returns>
        public static int StorageForTheMoment(string @strAppTID, int @intAppID, int @intIdeaFlag, string @strAppIdea, string @strDisCode, string @strUserCode, string @strAppDSIDs, string @strAppDSIDMs, string @strObject, string strAppOTitle, string InstanceID, int intAppOID, string strAppOValues)
        {
            DBOperator dalSql = DBOperatorFactory.GetDBOperator();
            object[] param = new object[] { @strAppTID, @intAppID, @intIdeaFlag, @strAppIdea, @strDisCode, @strUserCode, @strAppDSIDs, @strAppDSIDMs, @strObject, strAppOTitle, InstanceID, 0, intAppOID, strAppOValues };
            dalSql.ExecProcReobject("Pt_AppInstanceSave", param);
            if (dalSql.IsError)
                return 0;
            else
                return 1;
        }

        /// <summary>
        /// 保存表单实例
        /// </summary>
        /// <param name="InstanceID">实例ID</param>
        /// <param name="Name">表单实例的名称</param>
        /// <param name="URL">实例地址</param>
        /// <param name="AppDID">当前的流程步骤ID</param>
        /// <returns>true 成功，false失败</returns>
        public static bool SaveFormInstance(string InstanceID, string Name, string URL, int AppDID)
        {
            DBOperator dalSql = DBOperatorFactory.GetDBOperator();
            object[] obj = new object[] { InstanceID, Name, URL, AppDID };
            dalSql.ExecProcReInt("pt_AppInstanceForm", obj);
            return !dalSql.IsError;
        }
        /// <summary>
        /// 获取表单实例的地址
        /// </summary>
        /// <param name="AppDID">步骤ID</param>
        /// <param name="InstanceID">实例ID</param>
        /// <returns></returns>
        public static string GetFormInstance(int AppDID, string InstanceID)
        {
            DBOperator dalSql = DBOperatorFactory.GetDBOperator();
            object[] obj = new object[2];
            obj[0] = AppDID;
            obj[1] = InstanceID;
            string tempText;
            DataTable dt = dalSql.ExecProcReDataTable("pt_AppFormInstanceURL", obj);
            tempText = dt.Rows[0]["Form_URL"].ToString();
            if (dt == null || dt.Rows.Count == 0)
                if (dalSql.IsError)
                    return "";
            if (dt != null) dt.Dispose();
            return tempText;
            //
        }

        /// <summary>
        /// 流程发起第一步
        /// </summary>
        /// <param name="strUserCode"></param>
        /// <param name="strAppTID"></param>
        /// <param name="intAppDID"></param>
        /// <param name="intAppOID"></param>
        /// <param name="intAppValues"></param>
        /// <param name="strAppTitle"></param>
        /// <param name="intAppState"></param>
        /// <param name="strDateBeginTime"></param>
        /// <param name="strDateEndTime"></param>
        /// <param name="intTFlag"></param>
        /// <param name="InstanceID"></param>
        /// <returns></returns>
        public static int InsertFlowFirstStep(string strUserCode, string strAppTID, int intAppDID, int intAppOID, string intAppValues, string strAppTitle, int intAppState, string strDateBeginTime, string strDateEndTime, int intTFlag, string InstanceID)
        {
            JHSoft.WorkFlow.FlowInstanceRunning.ButtonNextImpl NextObj = new JHSoft.WorkFlow.FlowInstanceRunning.ButtonNextImpl();
            //流程第一个步骤所执行的插入方法会返回其插入到jhoa_approve表中的approveID
            DataSet dsAppID = NextObj.InsertNewApproveItem(strUserCode, strAppTID, intAppDID, intAppOID, intAppValues, strAppTitle, intAppState, strDateBeginTime, strDateEndTime, intTFlag, InstanceID);
            DataRow dr = dsAppID.Tables[0].Rows[0];
            int intReturnValue = -1;
            if (dr["App_ID"].ToString() != null || dr["App_ID"].ToString() != "")
                intReturnValue = Convert.ToInt32(dr["App_ID"].ToString());
            if (dsAppID != null) dsAppID.Dispose();
            return intReturnValue;
        }
        /// <summary>
        /// 获得用户姓名
        /// </summary>
        /// <param name="strUserCode"></param>
        /// <returns></returns>
        public static string GetUserName(string strUserCode)
        {
            DBOperator dalSql = DBOperatorFactory.GetDBOperator();
            string sql = "select top 1 UserName from vw_users where UserID='" + strUserCode + "' ";
            DataTable dt = new DataTable();
            dt = dalSql.ExecSQLReDataTable(sql);
            string tempText;
            tempText = dt.Rows[0]["UserName"].ToString();
            if (dalSql.IsError)
            {
                string aa = dalSql.ErrorMessage;
            }
            return tempText;
        }
        /// <summary>
        /// 创建流程模板实例
        /// </summary>
        /// <param name="TemplateID"> 模板ID</param>
        /// <param name="InstanceID">实例ID</param>
        /// <param name="InstanceName">实例名称</param>
        /// <param name="UserID">流程实例发起人ID</param>
        /// <returns>实行是否出错</returns>
        public static bool CreateFlowInstance(string TemplateID, string InstanceID, string InstanceName, string UserID, string Version)
        {
            DBOperator dalSql = DBOperatorFactory.GetDBOperator();
            if (InstanceName.Length > 100)
                InstanceName = InstanceName.Substring(0, 99);
            object[] obj = new object[6];
            obj[0] = TemplateID;
            obj[1] = InstanceID;
            obj[2] = InstanceName;
            obj[3] = UserID;
            obj[4] = "running";
            obj[5] = Version;

            dalSql.ExecProcReDataTable("pt_AppTempInstanceImpl", obj);
            return !dalSql.IsError;
        }

        /// <summary>
        /// 更具流程模板编号，获取表单相关信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static JHFlowInfo GetFlowInfo(WorkflowModel model)
        {
            return new JHFlowInfo
            {
                DjSN = "jgxmsq_09821ee0-26f3-4782-bb98-106615d5be7c",
                AppID = "34eba9d929a548aebc4b0ff4a68c56e2",
                UserCode = "w001"
            };
        }
        /// <summary>
        /// 通过表单djsnid获得表单内容
        /// </summary>
        /// <param name="djsn"></param>
        /// <returns></returns>
        public static string GetDJBiaoshi(string djsn)
        {
            DBOperator dalSql = DBOperatorFactory.GetDBOperator();
            string result = string.Empty;
            string strSql = "select xmltext from FC_BILLZL where djsn='{0}'";
            strSql = string.Format(strSql, djsn);
            DataSet ds = dalSql.ExecSQLReDataSet(strSql);
            string tempText;
            if (ds == null || ds.Tables[0].Rows.Count == 0) return "";
            else
            {
                tempText = ds.Tables[0].Rows[0]["xmltext"].ToString();
                Regex reg = new Regex("codeheader(?:=\"([\\s\\S]*?)\")?");
                Match mt = reg.Match(tempText);
                if (mt.Groups.Count > 0)
                {
                    result = mt.Groups[1].Value;
                }
            }
            if (ds != null) ds.Dispose();
            return result;
        }

        /// <summary>
        /// 根据表单标识id更新表单的recnum
        /// </summary>
        /// <param name="strCode"></param>
        /// <returns></returns>
        public static string UpdateDJBiaoshi_Recnum(string biaoshi)
        {
            DBOperator dalSql = DBOperatorFactory.GetDBOperator();
            string strSql = "select recnum from FC_MAXBH where biaoshi='{0}'";
            strSql = string.Format(strSql, biaoshi);
            DataSet ds = dalSql.ExecSQLReDataSet(strSql);
            string tempText;
            if (ds == null || ds.Tables[0].Rows.Count == 0)
            {
                tempText = biaoshi + "1".ToString().PadLeft((11 - biaoshi.Length), '0');
                strSql = string.Format("insert into FC_MAXBH(biaoshi,recnum) values('{0}','{1}')", biaoshi, "1");

            }
            else
            {
                tempText = biaoshi + (Convert.ToInt32(ds.Tables[0].Rows[0]["recnum"]) + 1).ToString().PadLeft((11 - biaoshi.Length), '0');
                strSql = string.Format("update FC_MAXBH set recnum = '{0}' where biaoshi = '{1}'", Convert.ToInt32(ds.Tables[0].Rows[0]["recnum"]) + 1, biaoshi);
            }

            dalSql.ExecSQLReInt(strSql);
            if (dalSql.IsError)
                return "";
            if (ds != null) ds.Dispose();
            return tempText;
        }

        /// <summary>	
        /// 根据流程appt_id,djsn获取流程版本信息及流程名称
        /// </summary>
        /// <param name="appt_id">当前流程appt_id</param>
        /// <param name="djsn">当前流程表单djsn</param>
        /// <returns>流程版本信息及流程名称</returns>
        public static JHFlowInfo GetTemplate(string appt_id, string djsn)
        {
            DBOperator dalSql = DBOperatorFactory.GetDBOperator();
            string strSql = string.Format("select Tem_Name,Tem_version from JHOA_APPROVE_Template where Tem_ID = '{0}' and Form_id='{1}' and Tem_CurVersion = 1", appt_id, djsn);
            using (DataSet dsTemplate = dalSql.ExecSQLReDataSet(strSql))
            {
                if (dsTemplate.Tables.Count > 0 && dsTemplate.Tables[0].Rows.Count > 0)
                {

                    return new JHFlowInfo
                    {
                        AppID = appt_id,
                        DjSN = djsn,
                        FlowTypeName = dsTemplate.Tables[0].Rows[0]["Tem_Name"].ToString(),
                        Version = dsTemplate.Tables[0].Rows[0]["Tem_Version"].ToString()
                    };
                }
            }
            return new JHFlowInfo();
        }
    }
}
